
const CACHE_NAME='ytd-tool-v1';
const ASSETS=['./index.html','./manifest.webmanifest','./icons/icon-192.png','./icons/icon-512.png'];
self.addEventListener('install',e=>{e.waitUntil(caches.open(CACHE_NAME).then(c=>c.addAll(ASSETS)))});
self.addEventListener('activate',e=>{e.waitUntil(caches.keys().then(keys=>Promise.all(keys.map(k=>k!==CACHE_NAME?caches.delete(k):Promise.resolve()))))});
self.addEventListener('fetch',e=>{
  const req=e.request;
  if(req.destination==='document'){
    e.respondWith(fetch(req).then(r=>{const c=r.clone();caches.open(CACHE_NAME).then(cache=>cache.put(req,c));return r;})
      .catch(()=>caches.match(req).then(r=>r||caches.match('./index.html'))));
  }else{
    e.respondWith(caches.match(req).then(r=>r||fetch(req).then(resp=>{const c=resp.clone();caches.open(CACHE_NAME).then(cache=>cache.put(req,c));return resp;})));
  }
});
